import os

from fastapi import APIRouter, UploadFile, Depends
from langchain_community.document_loaders import Docx2txtLoader
from starlette.responses import StreamingResponse, FileResponse

from agent.exam_agent import generate_exam_response
from agent.file_agent import generate_stream_response
from agent.ppt_agent import create_ppt
from models.json_response import JsonData
from service.file_service import FileService

router = APIRouter(
    prefix="/api/file",
    tags=["教学助手"]
)

@router.post("/outline")
async def outline(file:UploadFile,
                file_service:FileService=Depends(FileService),):
    content = file.file.read()
    file_location = os.path.join("./file", file.filename)
    with open(file_location, "wb") as f:
        f.write(content)
    loader= Docx2txtLoader(file_location)
    data = loader.load()
    return StreamingResponse(
        generate_stream_response(file_service, data),
        media_type="text/event-stream"
    )

@router.post("/exam")
async def exam(file:UploadFile,
               knowledge_point:str,
            file_service:FileService=Depends(FileService),):
    content = file.file.read()
    file_location = os.path.join("./file", file.filename)
    with open(file_location, "wb") as f:
        f.write(content)
    loader = Docx2txtLoader(file_location)
    data = loader.load()
    return StreamingResponse(
        generate_exam_response(file_service, data,knowledge_point),
        media_type="text/event-stream"
    )

@router.post("/ppt")
def ppt(file:UploadFile,
               pages:int,
            file_service:FileService=Depends(FileService)):
    data = file_service.load_file(file)
    chunks=""
    for chunk in data:
        chunks = chunks + chunk.page_content
    path = create_ppt(chunks,pages)
    return FileResponse(
        path=path,
        filename="ppt.pptx",
        media_type="application/octet-stream"
    )

